﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Pikapika.Models
{
    public partial class NovelChapter
    {

        private Lazy<IChapterContentStore> _store = new Lazy<IChapterContentStore>(() => ChapterContentStore.Instance);

        private string _chapterContent;
        private bool _chapterContentIsDirty;

        internal NovelChapter(Lazy<IChapterContentStore> store)
        {
            if (store == null)
                throw new ArgumentNullException("store", "store is null.");

            _store = store;
        }

        public NovelChapter()
            : this(new Lazy<IChapterContentStore>(() => ChapterContentStore.Instance))
        {

        }

        private bool CanPersistChapterContent()
        {
            return Id > 0
                && NovelVolumeId > 0
                && NovelId > 0;
        }
        private string LoadChapterContent()
        {
            if (!CanPersistChapterContent())
            {
                return null;
            }
            return _store.Value.LoadChapterContent(this);
        }

        public void SaveChapterContentIfNeeded()
        {
            if (!_chapterContentIsDirty || !CanPersistChapterContent())
            {
                return;
            }
            _chapterContentIsDirty = false;
            _store.Value.SaveChapterContent(this);
        }

        public string ChapterContent
        {
            get
            {
                if (_chapterContent == null)
                {
                    _chapterContent = LoadChapterContent();
                }
                return _chapterContent;
            }
            set
            {
                if (!string.Equals(value, _chapterContent))
                {
                    _chapterContent = value ?? string.Empty;
                    _chapterContentIsDirty = true;
                }
                SaveChapterContentIfNeeded();
            }
        }

        protected override void OnPropertyChanged(string property)
        {
            base.OnPropertyChanged(property);
            SaveChapterContentIfNeeded();
        }
    }
}